<template>
  <el-dialog
    :title="title"
    v-model="model"
    width="500px"
    :before-close="closeHandle"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input
          v-model="form.phone"
          type="input"
          placeholder="请输入电话号码"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>

    <template v-slot:footer>
      <div>
        <el-button @click="closeHandle">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { ElMessage } from "element-plus";
import { saveAddressBook, updateAddressBook } from "@/api/operateManage";

const props = defineProps({
  title: {
    type: String,
    default: "",
  },
  row: {
    type: Object,
    default: () => ({}),
  },
  communityId: {
    type: Number,
    required: true,
  },
});

const formRef = ref();
const isEdit = computed(() => !!props.row.id);

const emit = defineEmits(["submit"]);
const model = defineModel({
  default: false,
});

const form = ref({
  communityId: props.communityId,
  name: "",
  phone: "",
  remark: "",
});

const rules = reactive({
  name: [{ required: true, message: "请输入名称" }],
  phone: [{ required: true, message: "请输入电话号码" }],
});

onMounted(() => {
  if (isEdit.value) {
    form.value = { ...props.row };
  } else {
    form.value.communityId = props.communityId;
  }
});

const closeHandle = () => {
  model.value = false;
};

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const params = { ...form.value };
      if (isEdit.value) {
        params.id = props.row.id;
      }
      const api = isEdit.value ? updateAddressBook : saveAddressBook;
      api(params).then(() => {
        ElMessage({
          message: isEdit.value ? "编辑成功" : "添加成功",
          type: "success",
        });
        closeHandle();
        emit("submit", form.value);
      });
    }
  });
};
</script>

<style scoped>
.el-input,
.el-textarea {
  width: 100%;
}
</style>
